import { history } from 'umi';
import { message } from 'antd';
import { fakeAccountLogin, getFakeCaptcha } from './service';
import { getPageQuery, setAuthority } from './utils/utils';
import db from '@/utils/localstorage';

function saveLoginData(token){
  // db.save('JSESSIONID', token.token)
  // const current = new Date()
  // const expireTime = current.setTime(current.getTime() + 1000 * token.expire)
  // db.save('expireTime', expireTime)
}
function saveUserInfo(user, permissionsList,roles){
  db.save('user', user);
  db.save('roles', roles);
  db.save('permissions', permissionsList);
}

const Model = {
  namespace: 'userAndlogin',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

      if (response.code === 0) {
        message.success('登录成功！');
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;

        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        saveUserInfo(response.data.user,response.data.permissionsList,response.role);
        history.replace(redirect || '/');
      }else{
        message.warn(response.msg)
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority||'admin');
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
